package com.jddup.program;

import com.jddup.common.pojo.EntityAndDbDifference;
import com.jddup.common.pojo.JddupConfig;
import com.jddup.context.CompareContext;
import com.jddup.context.EntityTableMetaContext;
import com.jddup.context.JddConfigContext;
import com.jddup.program.comparator.CompatibilityStartup;
import com.jddup.program.config.ConfigLoader;
import com.jddup.program.config.ConfigLoaderImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Created by ZZB on 2017/12/4.
 */
public class Jddup {
    private static final Logger logger = LoggerFactory.getLogger(Jddup.class);
    private JddupConfig jddupConfig;

    public Jddup(JddupConfig jddupConfig) {
        this.jddupConfig = jddupConfig;
        init();
    }

    /**
     * 初始化
     */
    public void init() {
        ConfigLoader configLoader = new ConfigLoaderImpl();
        configLoader.load(jddupConfig);
        CompatibilityStartup compatibilityStartup = new CompatibilityStartup();
        compatibilityStartup.reload();
        if (jddupConfig.getOpenCompare()) {
            compatibilityStartup.startCompare();
        }
        if (jddupConfig.getAutoCreateTable()) {
            List<EntityAndDbDifference> notExistTable = CompareContext.getTableNameDifferencesMap().values().stream().
                    filter(t -> !t.getTableExist()).collect(Collectors.toList());
            notExistTable.forEach(entityAndDbDifference -> {
                String tableName = entityAndDbDifference.getTableName();
                String createTableDdl = entityAndDbDifference.getCreateTableDdl();
                logger.warn("检测到表 {} 不存在，正在执行创建表SQL \n{}",tableName,createTableDdl);
                String dbName = EntityTableMetaContext.getTableDataSourceMap().get(tableName);
                DataSource dataSource = JddConfigContext.getDataSourceMap().get(dbName);
                Connection connection = null;
                try {
                    connection = dataSource.getConnection();
                    Statement statement = connection.createStatement();
                    statement.execute(createTableDdl);
                    logger.warn("表 {} 创建完成！",tableName);
                } catch (SQLException e) {
                    logger.error("执行创建表SQL失败，表名{}, SQL {} , Ex {}",tableName,createTableDdl,e);
                } finally {
                    try {
                        if (connection != null) {
                            connection.close();
                        }
                    } catch (SQLException e) {
                        e.printStackTrace();
                    }
                }

            });
        }
    }
}
